<?php

class Yamarket_Model_OffersMapper{
	protected $_dbTable;
    protected $_dbView;
	
	public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable(){
        if (null === $this->_dbTable)
            $this->setDbTable('Yamarket_Model_DbTable_Offers');
        return $this->_dbTable;
    }
	
	public function fetchAll($query=null,$start=null,$limit=null){
		$t = $this->getDbTable();//new Yamarket_Model_DbTable_OffersAndNodes();
        $s = $t->select();
        if ((null!=$start) && (null!=$limit))
            $s->limit($limit,$start);
        if (null!=$query) $s->where(new Zend_Db_Expr("Vendor LIKE '%".$query."%' OR Model LIKE '%".$query."%'") );
		return $t->fetchAll($s)->toArray();
	}
    
    public function fetchForPublish(){
        $mapperTree = new Admin_Model_TreeNodeMapper();
        $t1 = $this->getDbTable();
        $t2 = $mapperTree->getDbTable();
        $set = $t1->fetchAll($t1->select()->setIntegrityCheck(false)
                            ->from(array('t1'=>$t1->info(Zend_Db_Table_Abstract::NAME)),Zend_Db_Select::SQL_WILDCARD)
                            ->join(array('t2'=>$t2->info(Zend_Db_Table_Abstract::NAME)),'t1.NodeId=t2.Id',array('URL','XML'))
                            ->where('(t1.Publish = 1) AND (t1.CategoryId IS NOT NULL)'));
        $result=array();
        foreach($set as $row){
            $r = $row->toArray();
            $node = $mapperTree->createNode(array('XML'=>$r['XML'],'URL'=>$r['URL']));
            unset($r['XML']);
            unset($r['URL']);
            $result[] = array(new Yamarket_Model_Offer($r),$node);
        }
        return  $result;
    }
    
    public function count(){
        $t = $this->getDbTable();
        $a=$t->fetchRow($t->select()->from($t,new Zend_Db_Expr("COUNT(Id) as C")))->toArray();
        return $a['C'];
    }
	public function updateByNodeId($params){
		$t = $this->getDbTable();
        $t->update($params,array('NodeId=?'=>$params['NodeId']));
	}
    
    public function save($params){
        $t = $this->getDbTable();
        if (isset($params['Id']))
            $t->update($params,array('Id=?'=>$params['Id']));
        else
            return $t->insert($params);
        return $params['Id'];
    }
    
    public function delete($id){
        $this->getDbTable()->delete(array('Id=?'=>$id));
    }
}
?>